--[[
    对局列表界面
]]--

local blaze  = require "blaze"
local app = require "app"
local game = require "club.threecard.sudoku"
local const = game.util.const

local M = game.ui.activity()

M.store_watchers = {
    async_game = {
        ["匹配状态变更"] = function(self, store, state, args)
            self.match_btn.gameObject:SetActive(not state.is_matching)
            self.unmatch_btn.gameObject:SetActive(state.is_matching)
        end,
        ["更新对局列表"] = function(self, store, state, args, init)
            self.versus_list:fill(state.versus_list)
        end,
        ["新对手"] = function(self, store, state, args, init)
            if init then
                return
            end
            game.audio.post("new-opponent")
            if self.new_opponent then
                self.new_opponent:set_versus(args)
            else
                self.new_opponent = require("club.threecard.sudoku.ui.versus.NewOpponentUI").new(args)
                self.new_opponent:load()
            end
            self.new_opponent:show()
        end
    }
}

function M:ctor()
    local LoopScrollList = require "blaze.ui.widget.LoopScrollList"
    local VersusListItem = require "club.threecard.sudoku.ui.versus.VersusListItem"

    self.res = "club.threecard.sudoku/ui/versus.b:VersusUI"
    self.versus_list = LoopScrollList.new()
    self.versus_list.res = "club.threecard.sudoku/ui/versus.b:versus_item"
    self.versus_list.create_item = function(_, data, index) return VersusListItem.new(data) end
end

function M:on_load()
    self:super("on_load")
    self.versus_list:load()
end

function M:on_injected(bind)
    bind("button.click", self.match_btn, self.on_match_click)
    bind("button.click", self.unmatch_btn, self.on_unmatch_click)
    bind("button.click", self.exit_btn, self.on_exit_click)
    bind("shortcut.escape", self.exit_btn.gameObject, self.on_exit_click)
    self.versus_list:attach(self.versus_scroll_rect)
end

function M.before_route_enter(to, from, next)
    next(app.kbe.player().async_game_api:query_versus_list())
end

function M:after_route_enter(to, from)
    self:super("after_route_enter", to, from)
    self.versus_list:refill()
end

function M:on_match_click()
    app.kbe.player().async_game_api:active_matching(const.ASYNC_GAME_ROOM_ID, true)
end

function M:on_unmatch_click()
    app.kbe.player().async_game_api:active_matching(const.ASYNC_GAME_ROOM_ID, false)
end

function M:on_exit_click()
    game.audio.post("click")
    game.router.back()
end

function M:on_release()
    self.versus_list:release()
end

return M